<?php
/**
 * Created by PhpStorm.
 * User: jin
 * Date: 2015/9/11
 * Time: 11:23
 */

namespace block;


class Block
{
    /**
     * 获取块内容
     * @param $blockName
     * @param int $id
     * @param string $parameter
     */
    static function getBlock($blockId,$id = 0,$parameter = array())
    {
        //获取块文件路径
        $blockPath = self::getBlockPath($blockId,$id);
        $blockContent = '';
        $content = '';
        try
        {
            //判断块文件是否存在
            if(!file_exists($blockPath)) throw new \Exception('文件不存在');

            $blockContent = unserialize(file_get_contents($blockPath));
            if(!isset($blockContent->time) || ((time() - (int)$blockContent->time) > (int)$blockContent->validTime)) throw new \Exception('超过有效时间');
            $content = $blockContent->content;
        }
        catch(\Exception $e)
        {
            $parameter['blockId'] = $blockId;
            $parameter['atId'] = $id;
            $passwordKey = \block\Conf::getPasswordKey();
            $password = \block\Conf::getPassword();
            $checkStr = \block\Passwd::passportEncrypt($password,$passwordKey);
//            echo \block\Passwd::passportDecrypt($checkStr,$passwordKey);
//            die();
            $parameter['checkStr'] = $checkStr;
            $blockContentTemp = $blockContent;
            $blockContent = self::getBlockForRemote($parameter);
//            if(!isset($blockContent->content)) $content = '';
            if(!empty($blockContent->content))
            {
                $content = $blockContent->content;
                \block\File::writeFile(serialize($blockContent),$blockPath);
            }
            else
            {
                $content = '';
                switch($e->getMessage())
                {
                    case '文件不存在':
                        $content = '';
                        break;
                    case '超过有效时间':
                        $content = $blockContentTemp->content;
                        break;
                }
                $blockContent = json_decode(json_encode(array('time'=>time(),'content'=>$content,'validTime'=>60*60*24*3)));
                \block\File::writeFile(serialize($blockContent),$blockPath);
            }
        }
        return htmlspecialchars_decode($content);
    }

    /**
     * 根据标签和id获取块路径
     * @param $blockName
     * @param int $id
     * @return string
     */
    static function getBlockPath($blockName,$id = 0)
    {
        $blockPath = '';
        if($id == 0)
        {
            $blockPath = \block\Conf::$blockCache.$blockName;
        }
        else
        {
            $blockPath = \block\Conf::$blockCache.$blockName.'/'.ceil($id/1000).'/'.$id;
        }
        return $blockPath;
    }
    static function getBlockForRemote($parameter,$maxCount = 3)
    {
        $blockContent = false;
        $blockContent = json_decode(removeBOM(\block\Curl::Post(\block\Conf::$blockRemoteUrl,$parameter)));
        //根据传递的次数尝试重复获取
//        while(((\block\Curl::$httpCode != 200) || !is_object($blockContent) || (get_class($blockContent) != 'stdClass')) && $i < $maxCount)
//        {
//            $blockContent = \block\Curl::Post(\block\Conf::$blockRemoteUrl,$parameter);
//            $i++;
//        }
        return $blockContent;
    }
}
function removeBOM($str = '')
{
    if (substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
        $str = substr($str, 3);
    }
    return $str;
}
require __DIR__.'/Conf.php';
new \block\Conf();
require \block\Conf::$blockPath.'Curl.php';
require \block\Conf::$blockPath.'Passwd.php';
require \block\Conf::$blockPath.'File.php';